<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\Admin\WebContent\CreateRequest;
use App\Http\Requests\Admin\WebContent\UpdateRequest;
use App\Models\Common\WebContent;
use App\Models\Common\WebContentImg;
use Illuminate\Http\Request;
use Style, DB;

class WebContentController extends CommonController{
    /**
     * 设置图片位置 返回json
     * @return \Illuminate\Http\JsonResponse
     */
    public function uploadUrl(){
        $json = preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents(app_path() . "/Vendor/Ueditor/config.json"));
        return response()->json(json_decode($json, true));
    }

    /**
     * 上传图片
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function webUploadUrl(Request $request){
        if($request->hasFile('upfile')){
            $file = $request->file('upfile');
            $entension = strtolower($file->getClientOriginalExtension());
            $mimeTye = $file->getMimeType();
            $clientName = $file->getClientOriginalName();//客服端文件名
            $size = $file->getSize();//文件大小

            if($file->isValid()){
                if(!in_array($entension, array('jpg', 'gif', 'png','jpeg','doc','docx','xlsx','xls','pdf','ppt','pptx','rar', 'zip', 'tar','txt'))){
                    return response()->json(['error' => 304, 'info' => "文件类型只能为jpg、gif、png、doc、xls、pdf、ppt、rar、zip、txt！"]);
                }else{
                    $fileurl = date("Ym") . '/';
                    $filename = time() . strtolower(str_random(5)) . '.' . $entension;
                    $request->file('upfile')->move(public_path() . '/upload/webcontent/' . $fileurl, $filename);
                    $data['news_id'] = 0;
                    $data['img_url'] = $fileurl . $filename;
                    $data['img_state'] = 0;
                    $data['img_tag'] = $request->img_tag;
                    if(WebContentImg::create($data)){
                        $return = array(
                            "state" => 'SUCCESS',
                            "url" => asset('upload/webcontent/' . $fileurl . $filename),
                            "title" => $clientName,
                            "original" => $clientName,
                            "type" => $mimeTye,
                            "size" => $size
                        );
                        return response()->json($return);
                    }
                }
            }
        }else{
            return response()->json(['error' => 306, 'info' => "没有选择上传图片文件！"]);
        }
    }

    /**
     * 底图上传
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bgImgUpload(Request $request){
        if($request->hasFile('file')){
            $file = $request->file('file');
            $entension = strtolower($file->getClientOriginalExtension());
            $mimeTye = $file->getMimeType();
            $clientName = $file->getClientOriginalName();//客服端文件名
            $size = $file->getSize();//文件大小
            if($file->isValid()){
                if(!in_array($entension, array('jpg', 'gif', 'png', 'jpeg'))){
                    return response()->json(['error' => 304, 'info' => "文件类型只能为jpg、gif、png！"]);
                }else{
                    $fileurl = date("Ym") . '/';
                    $filename = time() . strtolower(str_random(5)) . '.' . $entension;
                    public_path() . '/upload/webcontent/' . $fileurl;
                    $request->file('file')->move(public_path() . '/upload/webcontent/' . $fileurl, $filename);
                    $data['news_id'] = 0;
                    $data['img_url'] = $fileurl . $filename;
                    $data['img_state'] = 0;
                    $data['img_tag'] = $request->img_tag;
                    WebContentImg::create($data);
                    return response()->json(['status' => 200, 'url' => $fileurl . $filename, 'imgurl' => asset('upload/webcontent/' . $fileurl . $filename)]);
                }
            }else{
                return response()->json(['error' => 306, 'info' => "不是一个有效的文件！"]);
            }
        }
    }

    /**
     * 显示内容
     * @return mixed
     */
    public function index(Request $request){
        $webContent = WebContent::orderBy('descid', 'desc')->orderBy('updated_at', 'desc')->paginate(20);
        return Style::view('admin.webcontent.index', compact('webContent'));
    }

    /**
     * 添加内容
     * @return mixed
     */
    public function create(){
        $strRandom = str_random(40);
        return Style::view('admin.webcontent.create', compact("color", 'strRandom'));
    }

    /**
     * 添加内容提交
     * @param CreateRequest $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(CreateRequest $request){
        $input = $request->only(['title', 'sign', 'descid', 'editorvalue', 'img']);
        $input['created_at']=date('Y-m-d H:i:s',time());
        $input['updated_at']=date('Y-m-d H:i:s',time());
        $id = WebContent::insertGetId($input);
        if(!empty($id)){
            $this->delImg($id, $request);
            flash('添加内容管理成功', 'success');
            return redirect('admin/webcontent');
        }else{
            return back()->with('errors', '添加内容管理失败，请稍后重试！');
        }
    }

    /**
     * @param $id
     */
    public function show($id){
    }

    /**
     * 编辑内容
     * @param $id
     * @return mixed
     */
    public function edit($id){
        $webContent = WebContent::where('id', $id)->first();
        $webContentImg = WebContentImg::where('news_id', $id)->orderBy('created_at', 'desc')->first(['img_tag']);
        $webContent->img_tag = (!empty($webContentImg)) ? $webContentImg->img_tag : str_random(40);
        $webContent->img_url = !empty($webContent->img) ? asset('upload/webcontent/' . $webContent->img) : '';
        return Style::view('admin.webcontent.edit', compact("color", 'strRandom', 'webContent'));
    }

    /**
     * 更新内容
     * @param CreateRequest $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function update(UpdateRequest $request, $id){
        $input = $request->only(['title', 'sign', 'descid', 'editorvalue', 'img']);
        $result = WebContent::where('id', $id)->update($input);
        if(!empty($id)){
            $this->delImg($id, $request);
            flash('更新内容管理成功', 'success');
            return redirect('admin/webcontent');
        }else{
            return back()->with('errors', '更新内容管理失败，请稍后重试！');
        }
    }

    /**
     * 删除内容
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id){
        $result = WebContent::where('id', $id)->delete();
        if($result){
            //删除多余的图片
            $newWebContentImg = WebContentImg::where('news_id', $id)->get();
            if(!empty($newWebContentImg)){
                WebContentImg::where('news_id', $id)->delete();
                foreach($newWebContentImg as $v){
                    @unlink(public_path() . '/upload/webcontent/' . $v->img_url);
                }
            }
            return response()->json(['status' => 0, 'msg' => '删除内容管理成功！']);
        }else{
            return response()->json(['status' => 1, 'msg' => '删除内容管理失败，请稍后重试！']);
        }
    }


    /**
     * 根据跟踪标记删除图片
     * @param $id
     * @param $request
     */
    function delImg($id, $request){
        //根据跟踪标记取出内容图片表里面的图片
        $webContentImg = WebContentImg::select('id', 'news_id', 'img_url')->where('img_tag', $request->img_tag)->get();
        if(!empty($webContentImg)){
            $webContentImgId = [];
            /*获取内容详情取出图片*/
            $editorvalue = $request->editorvalue;
            preg_match_all('/<img\s+src=("|\')(.*)("|\')(\s+title(.*))?>/Uis', $editorvalue, $arr);
            if(count($arr[2]) > 0){
                foreach($arr[2] as $v){
                    foreach($webContentImg as $vv){
                        if(stristr($vv->img_url, basename($v))){
                            $webContentImgId[] = $vv->id;
                            break;
                        }
                    }
                }
            }
            /*获取背景图片*/
            $img_url = $request->img;
            if(!empty($webContentImg) && !empty($img_url)){
                foreach($webContentImg as $vvv){
                    if(strstr($vvv->img_url, $img_url)){
                        $webContentImgId[] = $vvv->id;
                        break;
                    }
                }
            }

            //更新内容图片
            if(count($webContentImgId) > 0){
                WebContentImg::whereIn('id', $webContentImgId)->update(['news_id' => $id, 'img_state' => 1]);
            }
            //删除多余的图片
            $newWebContentImg = WebContentImg::where('img_tag', $request->img_tag)->whereNotIn('id', $webContentImgId)->get();
            if(!empty($newWebContentImg)){
                WebContentImg::where('img_tag', $request->img_tag)->whereNotIn('id', $webContentImgId)->delete();
                foreach($newWebContentImg as $v){
                    @unlink(public_path() . '/upload/webcontent/' . $v->img_url);
                }
            }

        }
    }

    //-------------------------------------------------------------------------------------------------------------------------------------------

}